import axios, { AxiosRequestConfig } from 'axios';
import { AppKeyDefine } from './enum';
import { message } from 'antd';
const renewTokenUrl = '/api/System/ReNewToken';

interface ResponseResult<T = any> {
  success: boolean;
  msg?: string;
  exception?: string;
  data: T;
}

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求缺乏参数或参数格式不正确。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。你可能无权限访问该接口。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  429: '您的操作过于频繁。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

const getToken = () => {
  if (!window.token) {
    window.token = sessionStorage.getItem(AppKeyDefine.tokenKey) as string;
  }
  return window.token;
};
const getRefreshToken = () => {
  if (!window.refreshToken) {
    window.refreshToken = sessionStorage.getItem(AppKeyDefine.refreshTokenKey) as string;
  }
  return window.refreshToken;
};
const setToken = (token?: string) => {
  if (!token) {
    return;
  }
  window.token = token;
  sessionStorage.setItem(AppKeyDefine.tokenKey, token);
};
const setRefreshToken = (refreshToken?: string) => {
  if (!refreshToken) {
    return;
  }
  window.refreshToken = refreshToken;
  sessionStorage.setItem(AppKeyDefine.refreshTokenKey, refreshToken);
};

const abort = new AbortController();
axios.defaults.withCredentials = true;
const singleInstance = axios.create({
  timeout: 6000,
  // baseURL: 'https://118.31.15.75:18486',
  validateStatus: function (status) {
    return true;
  },
});

const defaultConfig: AxiosRequestConfig = {
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    Authorization: 'Bearer ' + getToken(),
  },
};

function RequestNet<T>(config: AxiosRequestConfig): Promise<T> {
  return new Promise((resolve, reject) => {
    singleInstance
      .request({
        ...defaultConfig,
        ...config,
        signal: abort.signal,
      })
      .then((res) => {
        switch (res.status) {
          case 401:
            if (getRefreshToken() && getToken()) {
              // authErrorStatus = true;
              axios
                .create()
                .get(renewTokenUrl, {
                  params: {
                    expriedToken: getToken(),
                    refreshToken: getRefreshToken(),
                  },
                })
                .then((res) => {
                  setToken(res.data.data?.AccessToken);
                  setRefreshToken(res.data.data?.RefreshToken);
                  return singleInstance(res.config);
                })
                .catch((err) => {
                  return Promise.reject(err);
                });
            }
            return Promise.reject(res.data);
          // break;
          case 404:
            // const { msg } = res.data
            const tips = `[${res.status}]${codeMessage[res.status] || ''} ${res?.data.msg || ''}`;
            // if (!config['disableErrorAlarm']) {
            //   Msg.error('请求错误:' + tips, { autoClose: 5000 });
            // }
            message.error('请求错误:' + tips);
            reject(new Error(tips));
            break;

          default:
            const { data, msg, success } = res.data || {};
            console.log(res.data)
            if (success) {
              resolve(data);
              break;
            }
            reject(new Error(msg));
            message.error(msg)
            break;
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
}

export { RequestNet, getToken, getRefreshToken, setToken, setRefreshToken };
